import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
  },
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.NoSign).ohpmInstall(IsEnable.Enable).build();

const PROTOBUFJS = 'protobuf.js';

const testCaseFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const modulePath = path.resolve(projectRootPath, 'shareLibrary');
  const protobufjsFile = path.resolve(modulePath, 'src/main/ets', PROTOBUFJS);

  // 在hsp 模块的 src/main/ets 目录下面新建1个 protobuf.js文件，里面使用 commonjs 导出
  await fse.appendFile(protobufjsFile, 'module.exports = {name:"name"}');
  expect(fse.existsSync(protobufjsFile));

  // 执行 hsp 模块 ohosTest 覆盖率插装
  const commands =
    // eslint-disable-next-line max-len
    '--mode module -p module=shareLibrary@default -p isOhosTest=true -p product=default -p buildMode=test -p ohos-test-coverage=true assembleHsp --analyze=normal --parallel --incremental --no-daemon'.split(
      ' ',
    );

  const result = await runHvigorAsync(projectRootPath, commands);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  // 检查没有插装错误出现
  expect(result.stdout).not.toContain('instrument failed, error:Error: ENOENT: no such file or directory');
};

TestCaseBuilder.builder()
  .caseName('DTS2024101718433')
  .description('测试覆盖率插桩未生成.test文件夹, hsp 里面有 protobuf.js 文件时覆盖率插桩报错')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testCaseFun)
  .load();
